define(function(require, exports, module) {
    'use strict';
    
    var rk = require('rk');
    
    

  // "maxGridRowCount": 5,
  // "maxGridColCount": 6,
  

    $.widget('rk.xsyReferGridView', $.rk.xsyBase, {
        options: {
        },
        _create: function(){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            elem.attr('wtype', 'xsyReferGridView')
            elem.attr('is-private', 'true');

            var gridConfig = {
                numberType : 'percentage',
                columns: me._getColumnsByServerData(opt.ownerData),
                lastColumnWidth: 32
            };

            elem.subgrid(gridConfig);
        },
        // _processEntityData: function(entityData){
        //     //有些item项没有label和value，因此确保进入grid时都有
        //     for(var i=0,len=entityData.length;i <len;i++){
        //         var entityrow = entityData[i];
        //         for(var key in entityrow){
        //             if(typeof entityrow[key] != 'object') entityrow[key] = {
        //                 label: entityrow[key],
        //                 value: entityrow[key]
        //             }
        //         }
        //     }
        //     return entityData;
        // },
        bindData: function(ownerData){
            var me = this;
            var elem = me.element;
            var opt = me.options;
            
            if(!ownerData.entityData)return;
            ownerData = $.extend(true, {}, ownerData);

            var itemList = ownerData.itemList;//列信息
            var entityData = ownerData.entityData//数据
            //entityData = me._processEntityData(entityData);

            me._processItemList(itemList);

            var MAX_ROWS = opt.maxRows;
            if(MAX_ROWS > entityData.length) MAX_ROWS = entityData.length;

            var data = [];
            for(var i=0,len=MAX_ROWS;i <len;i++){
                var edata = entityData[i];
                data.push(edata);
            }
            
            elem.subgrid('load', data);
        },
        _getColumnsByServerData: function(serverData){
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if(!serverData.itemList)return [];
            var maxCol = opt.maxCols;

            var columns = [];
            var percentage = 100 / serverData.itemList.length;
            var count = 0;
            for(var i = 0, len = serverData.itemList.length;i <len;i++){
                if(count < maxCol){
                    var item = serverData.itemList[i];
                    var type = item.itemType;
                    columns.push({
                            title: item.label,
                            attrs: ['itemname='+item.name],
                            //cellTmpl: '{{'+item.name+'.formatText}}',
                            cellRender: function(colInfo, rowData){
                                var cellData = rowData[colInfo.itemName];
                                var text = me._getDisplayingHtml({
                                    colIdx: colInfo.colIdx
                                }, colInfo.itemInfo, rowData, cellData, colInfo.itemType);
                                return text;
                            },
                            itemType: type,
                            itemName: item.name,
                            itemInfo: JSON.stringify(item),
                            width: percentage + '%'
                    });
                }
                count++;
            }
            if(opt.ownerConfig.showEntityMenu){
                columns.push({
                        title: '&nbsp;',
                        cellTmpl: '<div class="xsy_su_refer_card_toolbar">'+
                                  '  {{if permissions && permissions._showmenu !== false}}  <a href="javascript:;"><i class="xsy_su_refer_arrow"></i></a>{{/if}}'+
                                  '</div>',
                        width: 30
                });                
            }
            return columns;
        },
        _itemListCache: {},
        _processItemList: function(itemList){
            var me = this;
            //有些item项没有label和value，因此确保进入grid时都有
            for(var i=0,len=itemList.length;i <len;i++){
                var item = itemList[i];
                var name = item.name;
                if(item.itemTypeEntry) item.itemType = item.itemTypeEntry;//TODO：需要在数据端修正，此处仅是临时措施
                me._itemListCache[name] = item;//cache
            }
            return itemList;
        },
        _getDisplayingHtml: function(renderInfo, itemInfo, rowData, data, type){
            var me = this;
            var opt = me.options;
            var label;
            itemInfo = JSON.parse(itemInfo);
            var itemName = itemInfo.name;
            if(!data) return '';
            if(opt.ownerConfig.itemRender && $.isFunction(opt.ownerConfig.itemRender[itemName])){//自定义渲染
                return opt.ownerConfig.itemRender[itemName](rowData, data, type);
            }
            if($.isArray(data)){
                label = '';
                for(var i=0, len=data.length;i<len;i++){
                    label += (i>0?',':'') + data[i].label;
                }
                return label;
            }
            if(typeof data == 'object'){
                label = data ? data.label : '';
            }else{
                label = data ? data : '';
            }
            if(!data)return '';

            label = rk.htmlEscape(label);

            if(renderInfo.colIdx === 0){
                //第一列特殊处理，【注意】该问题只有grid才有，因为card视图强制不显示第一列
                var linkTpl = opt.ownerConfig.linkOfFinal;
                linkTpl = linkTpl ? linkTpl : '';
                var finalUrl = rk.templateText(linkTpl, rowData);
                if(rowData.permissions && rowData.permissions.view === false){
                    return '<a href="javascript:$.msg(\'无权限查看详情\');" class="xsy_su_refer_card_link" refid="'+rowData.id+'">'+(rowData.name?rk.htmlEscape(rowData.name):'')+'</a>';
                }else{
                    return '<a target="_blank" href="'+finalUrl+'" class="xsy_su_refer_card_link" refid="'+rowData.id+'">'+(rowData.name?rk.htmlEscape(rowData.name):'')+'</a>';
                }
            }
            if(data.icon){
                return '<a class="username" href="/final/user.action?uid='+data.value+'" ucard="uid='+data.value+'" target="_blank">'+data.label+'</a>'
            }else if(itemInfo.currencyFlg){
                return '￥' + numeral(label).format('0,0.[00]')
            }else if(itemInfo.itemType == 26 && itemInfo.joinItem && itemInfo.joinItem.itemType == 7){
                return Globalize.format(new Date(data - 0), 'yyyy-MM-dd');
            }else if (itemInfo.itemType == 6){
                return $.formatNumber(label, itemInfo.resolution, true);
            }else if(itemInfo.itemType == 27){
                if(itemInfo.formulaDataType == 6){
                    return $.formatNumber(label, itemInfo.resolution, true);
                }
            }else{
                return rk.formatText(label, type);
            }
        }
    });
});